﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Ue.Infrastructure;
using Ue.Infrastructure.DomainBase;
using Ue.Infrastructure.RepositoryFramework.Repository;
using Ue.Qcdz.Domain.Roles;
using Ue.Qcdz.Domain.TheResource;

namespace Ue.Qcdz.Repositories.TheResource
{
    public class ResourceRepository : SqlServerRepository<Resource>,IResourceRepository
    {
        public ResourceRepository()
            : this(null) { }

        public ResourceRepository(IUnitOfWork uniteOfWork)
            : base(uniteOfWork)
        {

        }

        #region Overrides of SqlServerRepositoryBase<Resource>

        protected override string GetDataTableName()
        {
            return "Resource";
        }

        protected override string[] GetBaseInsertFields()
        {
            return new string[]
                       {
                           ResourceFactory.FieldNames.EntityKey,
                           ResourceFactory.FieldNames.Name,
                           ResourceFactory.FieldNames.Num
                       };
        }

        protected override string[] GetBaseUpdateFields()
        {
            return new string[]
                       {
                           ResourceFactory.FieldNames.Name,
                           ResourceFactory.FieldNames.Num
                       };
        }

        protected override IDataParameter[] BuildParameters(Resource entity)
        {
            return new IDataParameter[]
                       {
                           RepositoryDriver.BuildParameter(ResourceFactory.FieldNames.EntityKey,entity.Key),
                           RepositoryDriver.BuildParameter(ResourceFactory.FieldNames.Name,entity.Name),
                           RepositoryDriver.BuildParameter(ResourceFactory.FieldNames.Num,entity.Num)
                       };
        }

        protected override IWhereClause BuildWhereClauseBy(IDataQuery dataQuery)
        {
            return null;
        }

        protected override IDictionary<string, ChildDataHandler> GetBuildEntityChildCallbacks()
        {
            return null;
        }
        protected override string GetOrderBy()
        {
            return null;
        }
        #endregion

        #region Implementation of IResourceRepository
        public IList<Resource> FindBy(Role role)
        {
            const string query = "select * from Resource where exists(select * from RoleInResource where RoleInResource.ResourceId=Resource.Id  and RoleInResource.RoleId=@RoleId)";
            return this.BuildEntitiesFromSql(query, this.RepositoryDriver.BuildParameter("@RoleId", role.Key));
        }

        #endregion

        
    }
}
